<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>摄像头</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="https://cdn.bootcss.com/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <style type="text/css">
        html, body {
            margin: 0px;
            padding: 0px;
        }

        #content {
            width: 100%;
            height: 100%;
        }

        #video {
            width: 100%;
            /*height: 90%;*/
            display: block;
            background-color: #eee;
            margin-bottom: 10px;
            border: 1px dotted #888;
        }

        #canvas {
            display: none;
        }

        #preview {
            display: none;
        }

        #response {

        }
    </style>
</head>
<body>
<div id="content">
    <video id="video" autoplay playsinline></video>
    <form class="container">
        <div class="form-group">
            <select id="select" class="form-control"></select></div>
        <div class="form-group">
            <button id="start" type="button" class="form-control btn btn-info">开始</button>
        </div>
        <div class="form-group">
            <button id="capture" type="button" class="form-control btn btn-primary">截图并上传</button>
        </div>
        <div class="form-group">
            <button id="stop" type="button" class="form-control btn btn-warning">结束</button>
        </div>
        <div class="form-group">
            <input type="text" id="input" class="form-control" placeholder="请输入图片上传url"
                   value="https://0edebe06.ngrok.io/upload">
        </div>
    </form>
    <canvas id="canvas"></canvas>
    <img id="preview" src="#">
    <p id="response"></p>
</div>
</body>
<script type="text/javascript">
    var video = document.querySelector('#video');
    var select = document.querySelector('#select');
    var start = document.querySelector('#start');
    var stop = document.querySelector('#stop');
    var capture = document.querySelector('#capture');
    var canvas = document.querySelector('#canvas');
    var preview = document.querySelector('#preview');
    var input = document.querySelector('#input');
    var response = document.querySelector('#response');
    var currentStream = undefined;

    function stopMediaTracks(stream) {
        var tracks = stream.getTracks();
        for (var i = 0; i < tracks.length; i++) {
            var track = tracks[i];
            track.stop();
        }
    }

    function gotDevices(mediaDevices) {
        select.innerHTML = '';
        var count = 1;
        for (var i = 0; i < mediaDevices.length; i++) {
            var mediaDevice = mediaDevices[i];
            if (mediaDevice.kind === 'videoinput') {
                var option = document.createElement('option');
                option.value = mediaDevice.deviceId;
                var label = mediaDevice.label || `Camera ${count++}`;
                var textNode = document.createTextNode(label);
                option.appendChild(textNode);
                if (i == 0) {
                    option.selected = true;
                }
                select.appendChild(option);
            }
        }
    }

    capture.addEventListener('click', function (event) {
        if (typeof currentStream === 'undefined') {
            alert('请开启摄像头');
            return;
        }
        canvas.width = video.videoWidth * 0.1;
        canvas.height = video.videoHeight * 0.1;
        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
        preview.src = canvas.toDataURL('image/png', 0.1);

        var url = input.value;
        $.ajax({
            type: 'POST',
            url: url,
            processData: false,
            data: preview.src,
            success: function (data) {
                response.innerText = JSON.stringify(data);
                alert(JSON.stringify(data));
            },
            error: function (xhr, status, error) {
                alert(error);
            },
            dataType: 'json'
        });
    });

    stop.addEventListener('click', function (event) {
        if (typeof currentStream !== 'undefined') {
            stopMediaTracks(currentStream);
        }
    });

    start.addEventListener('click', function (event) {
        if (typeof currentStream !== 'undefined') {
            stopMediaTracks(currentStream);
        }
        var videoConstraints = {};
        if (select.value === '') {
            videoConstraints.facingMode = 'environment';
        } else {
            videoConstraints.deviceId = {exact: select.value};
        }
        var constraints = {
            video: videoConstraints,
            audio: false
        };

        navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
            currentStream = stream;
            video.srcObject = stream;
            return navigator.mediaDevices.enumerateDevices();
        }).then(gotDevices).catch(function (err) {
            alert(err.name + ':' + err.message);
        });
    });

    navigator.mediaDevices.enumerateDevices().then(gotDevices);
</script>
</html>